<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish">
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name"/>
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
          v-model:value="ruleForm.alloy_code"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in alloyCodeSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="数据来源" name="data_source">
      <a-input v-model:value="ruleForm.data_source"/>
    </a-form-item>
    <a-form-item label="样品状态" name="sample_status">
      <a-input v-model:value="ruleForm.sample_status"/>
    </a-form-item>
    <a-form-item label="设备名称" name="equipment_name">
      <a-input v-model:value="ruleForm.equipment_name"/>
    </a-form-item>
    <a-form-item label="设备厂家" name="equipment_manufacturer">
      <a-input v-model:value="ruleForm.equipment_manufacturer"/>
    </a-form-item>
    <a-form-item label="设备型号" name="device_model">
      <a-input v-model:value="ruleForm.device_model"/>
    </a-form-item>
    <a-form-item label="压缩速率" name="compress_rate">
      <a-input v-model:value="ruleForm.compress_rate"/>
    </a-form-item>
    <a-form-item label="样品高度" name="sample_height">
      <a-input v-model:value="ruleForm.sample_height"/>
    </a-form-item>
    <a-form-item label="样品直径" name="sample_diameter">
      <a-input v-model:value="ruleForm.sample_diameter"/>
    </a-form-item>
    <a-form-item label="长" name="sample_length">
      <a-input v-model:value="ruleForm.sample_length"/>
    </a-form-item>
    <a-form-item label="宽" name="sample_width">
      <a-input v-model:value="ruleForm.sample_width"/>
    </a-form-item>
    <a-form-item label="试验温度" name="test_temperature">
      <a-input v-model:value="ruleForm.test_temperature"/>
    </a-form-item>
    <a-form-item label="压缩模量" name="compression_modulus">
      <a-input v-model:value="ruleForm.compression_modulus"/>
    </a-form-item>
    <a-form-item label="屈服强度" name="yield_strength">
      <a-input v-model:value="ruleForm.yield_strength"/>
    </a-form-item>
    <a-form-item label="极限抗压强度" name="ultimate_compress_strength">
      <a-input v-model:value="ruleForm.ultimate_compress_strength"/>
    </a-form-item>
    <a-form-item label="断裂强度" name="fracture_strength">
      <a-input v-model:value="ruleForm.fracture_strength"/>
    </a-form-item>
    <a-form-item label="断后延伸率" name="break_elongation">
      <a-input v-model:value="ruleForm.break_elongation"/>
    </a-form-item>
    <a-form-item label="压缩应力-应变曲线" name="compress_stress_strain">
      <a-upload
          :fileList="ruleForm.compressStressStrainList"
          :beforeUpload="beforeCompressStressStrainUpload"
          :headers="headers"
          @change="handleCompressStressStrainChange"
      >
        <a-button>
          <upload-outlined/>
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import {message} from 'ant-design-vue'
import {UploadOutlined} from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditCompactionMechanicalProperty',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    // validStr 不包含空格
    let validateAlloyName = async (rule, value) => {
      if (value === ''){
        return Promise.reject('请选择合金代码')
      }
    }
    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        data_source: '',
        sample_status: '',
        equipment_name: '',
        equipment_manufacturer: '',
        device_model: '',
        compress_rate: '',
        sample_height: '',
        sample_diameter: '',
        sample_length: '',
        sample_width: '',
        test_temperature: '',
        compression_modulus: '',
        yield_strength: '',
        ultimate_compress_strength: '',
        fracture_strength: '',
        break_elongation: '',
        compressStressStrainList: [],
      },
      rules: {
        alloy_code: [
          {
            validator: validateAlloyName,
            trigger: 'change',
            required: true,
            whiteSpace: true,
          }
        ],
      },
      layout: {
        labelCol: {span: 6},
        wrapperCol: {span: 14},
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.alloyCodeSelectionOptions = []
      this.axios
          .get('/attachment_management/alloy_phase_diagram/')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.alloyCodeSelectionOptions.push({
                url: data[i].url,
                label: data[i].alloy_code,
              })
            }
            this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
            if (this.url !== '') {
              this.axios
                  .get(this.url)
                  .then((res) => {
                    const data = res.data
                    this.ruleForm.sample_name = data.sample_name
                    this.ruleForm.alloy_code = data.alloy_code
                    this.ruleForm.data_source = data.data_source
                    this.ruleForm.sample_status = data.sample_status
                    this.ruleForm.equipment_name = data.equipment_name
                    this.ruleForm.equipment_manufacturer = data.equipment_manufacturer
                    this.ruleForm.device_model = data.device_model
                    this.ruleForm.compress_rate = data.compress_rate
                    this.ruleForm.sample_height = data.sample_height
                    this.ruleForm.sample_width = data.sample_width
                    this.ruleForm.sample_height = data.sample_height
                    this.ruleForm.sample_diameter = data.sample_diameter
                    this.ruleForm.sample_length = data.sample_length
                    this.ruleForm.sample_width = data.sample_width
                    this.ruleForm.test_temperature = data.test_temperature
                    this.ruleForm.compression_modulus = data.compression_modulus
                    this.ruleForm.yield_strength = data.yield_strength
                    this.ruleForm.ultimate_compress_strength =
                        data.ultimate_compress_strength
                    this.ruleForm.fracture_strength = data.fracture_strength
                    this.ruleForm.break_elongation = data.break_elongation
                    this.ruleForm.compress_stress_strain = data.compress_stress_strain
                    // 若有附件，则装入列表
                    if (data.compress_stress_strain_filename !== '') {
                      this.ruleForm.compressStressStrainList.push({
                        uid: '-1',
                        name: data.compress_stress_strain_filename,
                      })
                    }
                  })
                  .catch((error) => {
                    console.log('Error', error.message)
                  })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
            this.ruleForm.alloy_code = ''
          })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      const {
        compressStressStrainList
      } = this.ruleForm
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('data_source', values.data_source)
      formData.append('sample_status', values.sample_status)
      formData.append('equipment_name', values.equipment_name)
      formData.append('equipment_manufacturer', values.equipment_manufacturer)
      formData.append('device_model', values.device_model)
      formData.append('compress_rate', values.compress_rate)
      formData.append('sample_height', values.sample_height)
      formData.append('sample_diameter', values.sample_diameter)
      formData.append('sample_length', values.sample_length)
      formData.append('sample_width', values.sample_width)
      formData.append('test_temperature', values.test_temperature)
      formData.append('compression_modulus', values.compression_modulus)
      formData.append('yield_strength', values.yield_strength)
      formData.append('ultimate_compress_strength', values.ultimate_compress_strength)
      formData.append('fracture_strength', values.fracture_strength)
      formData.append('break_elongation', values.break_elongation)
      compressStressStrainList.forEach((file) => {
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file){
                  formData.append('compress_stress_strain', file.originFileObj)
        }
      })
      if (this.url !== '') {
        // 若文件列表为空，则附加属性通知后端
        if (this.ruleForm.compressStressStrainList.length === 0){
          formData.append('compress_stress_strain_empty', true)
        }
        this.axios
            .put(this.url, formData)
            .then(() => {
              this.submitting = false
              message.success('修改成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('修改失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      } else {
        this.axios
            .post('/property_management/compress_property/', formData)
            .then(() => {
              this.submitting = false
              message.success('添加成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('添加失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      }
    },
    beforeCompressStressStrainUpload(file) {
      this.ruleForm.compressStressStrainList = [
        ...this.ruleForm.compressStressStrainList,
        file,
      ]
      return false
    },
    handleCompressStressStrainChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.compressStressStrainList = fileList
    },

  },
}
</script>
